package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.service.LogService;
import com.tanhua.model.db.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;


import java.util.Date;
import java.util.Map;

/**
 * 日志监听处理类
 */
@Component
@Slf4j
public class LogListener {

    @Autowired
    private LogService logService;

    /**
     * 从tanhua.log.exchange交换机  路由key log.movement 获取消息
     * @Queue(value = "tanhua.log.queue",durable = "true"):配置队列名称（唯一） durable = "true":持久化
     * exchange = @Exchange(value = "tanhua.log.queue",type = ExchangeTypes.TOPIC), 配置交换器名称（发送消息交换器名称一样） 主题模式
     *  key = {"log.*"}：绑定key
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "tanhua.log.queue",durable = "true"),
            exchange = @Exchange(value = "tanhua.log.exchange",type = ExchangeTypes.TOPIC),
            key = {"log.*"}
    ))
    public void addLog(String message){
        //1.将messag转为map1
        Map<String,String> messageMap = JSON.parseObject(message, Map.class);
        if (messageMap!=null){
            String userId = messageMap.get("userId");
            String type = messageMap.get("type");
            String logTime = messageMap.get("logTime");
            String busId = messageMap.get("busId");
            //2.将消息内容设置Log对象中 保存日志
            log.debug("*********************addLog**********************" + message);
            Log myLog= new Log();
            myLog.setUserId(Long.valueOf(userId));
            myLog.setType(type);
            myLog.setCreated(new Date());
            myLog.setEquipment("IPHONE");
            myLog.setPlace("China");
            logService.add(myLog);
            log.debug("*********************记录日志成功了**********************");

        }
    }

}
